const { bannerModel } = require("../model")

//添加轮播图
exports.addBanner = async (req,res)=>{
    const { bannerUrl , isShow } = req.body
    let dbBack = new bannerModel({
        bannerUrl,
        isShow
    })
    try {
        await dbBack.save()
        res.status(200).json({
            code:200,
            message:'添加成功',
            data:null
        })
    } catch (error) {
        res.status(500).json({
            code:500,
            message:'添加失败',
            data:error
        })
    }
}
//获取轮播图列表
exports.getBanner = async (req,res)=>{
    const { pageNo=1,pageSize=5 } = req.query
    try {
        let result = await bannerModel.find().skip((pageNo-1)*pageSize).limit(pageSize)
        let total = await (await bannerModel.find()).length
        res.status(200).json({
            code:200,
            message:'获取成功',
            data:result,
            total
        })
    } catch (error) {
        res.status(500).json({
            code:500,
            message:'获取失败',
            data:error
        })
    }
}
//获取轮播图列表(前台用)
exports.getBannerList = async (req,res)=>{
    try {
        let result = await bannerModel.find({ isShow:1 })
        res.status(200).json({
            code:200,
            message:'获取成功',
            data:result
        })
    } catch (error) {
        res.status(500).json({
            code:500,
            message:'获取失败',
            data:error
        })
    }
}
//修改轮播图
exports.updateBanner = async (req,res)=>{
    const { id } = req.query
    const { bannerUrl , isShow } = req.body
    if(!id){
        return res.status(400).json({
            code:400,
            message:'id不能为空',
            data:null
        })
        
    }
    if(isShow==undefined){
        return res.status(400).json({
          code:400,
          message:'信息不全',
          data:null
        })
    }
    try {
        await bannerModel.updateOne({_id:id},{bannerUrl,isShow})
        res.status(200).json({
            code:200,
            message:'修改成功',
            data:null
        })
    } catch (error) {
        res.status(500).json({
            code:500,
            message:'修改失败',
            data:error
        })
    }
}
//删除轮播图
exports.deleteBanner = async (req,res)=>{
    const { id } = req.query
    if(!id){
        return res.status(400).json({
            code:400,
            message:'id不能为空',
            data:null
        })
    }
    try {
        await bannerModel.deleteOne({_id:id})
        res.status(200).json({
            code:200,
            message:'删除成功',
            data:null
        })
    } catch (error) {
        res.status(500).json({
          code:500,
          message:'服务器出现问题，请稍后重试',
          data:error
        })
    }
}